package fifthquestion;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class MsgReceiver {
        public static void main(String[] args) {
            //声明数据包Socket
            DatagramSocket ds = null;
            //声明数据报文(数据报文表示通信的一种报文类型,作用主要是用来封装数据)
            DatagramPacket dp = null;
            //创建文本扫描器
            Scanner input = new Scanner(System.in);
            //声明临时存放数据的缓冲区
            byte[] byteBuffer = new byte[1024];
            //创建InetAddress对象
            String host = "127.0.0.1";
            int port = 8800;

            //声明一个缓冲区
            byte[] dataBuffer = null;
            try {
                //创建数据报套接字
                ds = new DatagramSocket(port);
                System.out.println("客服人员已经上线啦，可以咨询了!!");
                String message = null;
                String information = null;
                InetAddress serverAddr = InetAddress.getByName(host);
                while(true){
                    //创建空的数据报包，准备接收发送者发送过来的数据
                    dp = new DatagramPacket(byteBuffer,byteBuffer.length);
                    System.out.println("111111111111111");
                    //接收数据包
                    ds.receive(dp);
                    System.out.println("222222222222222");
                    //解析数据包
                    message = new String(dp.getData(),0,dp.getLength());
                    System.out.println(message);

                    //=========================================================//
                    //回应咨询者
                    System.out.print("请输入消息：");
                    information = input.next();
                    dataBuffer = information.getBytes("utf-8");
                    dp = new DatagramPacket(dataBuffer,0,dataBuffer.length,dp.getSocketAddress());
                    ds.send(dp);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(ds != null){
                    ds.close();
                }
            }
        }

    }


